package com.yunzhou.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yunzhou.properties.QiniuyunProperties;
import com.yunzhou.service.QiniuyunService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.net.URLEncoder;

@Service
public class QiniuyunServiceImpl implements QiniuyunService {

    @Autowired
    private QiniuyunProperties qiniuyunProperties;

    // 上传文件
    @Override
    public String uploadFile(MultipartFile file, String filePath) {

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = qiniuyunProperties.getAccessKey();
        String secretKey = qiniuyunProperties.getSecretKey();
        String bucket = qiniuyunProperties.getBucket();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        // 将传递进来的文件路径作为key
        String key = filePath;

        try {
            byte[] bstream = file.getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bstream);

            // 上传文件
            Response response = uploadManager.put(byteInputStream, key, upToken,null, null);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println("key: "+putRet.key);
            System.out.println("hash: "+putRet.hash);
            System.out.println(qiniuyunProperties.getDomain() + putRet.key);

            // 修改编码方式
            // String encodedFileName = URLEncoder.encode(putRet.key, "utf-8");
            return qiniuyunProperties.getDomain() + putRet.key;
        } catch (QiniuException ex) {
            ex.printStackTrace();
            throw new RuntimeException("文件上传失败1");
        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("文件上传失败2");
        }
    }

}
